﻿
using Ec.NETCoreFramework.Common.Core.Helpers;
using Ec.NETCoreFramework.Common.Core.Serializer;
using System;
using System.Collections.Generic;

namespace Ec.NETCoreFramework.Common.Cache
{
    /// <summary>
    /// set
    /// </summary>
    public class RedisSetService : RedisDataBaseManager
    {
        public RedisSetService(string server, string password, int dbId):base(server,password,dbId)
        {
            
        }
        /// <summary>
        /// 批量插入set
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public void BatchSet<T>(string key, List<T> list)
        {
            var batch = _Database.CreateBatch();
            foreach (var item in list)
            {
                byte[] bytes = ByteSerializer.Serialize(item);
                batch.SetAddAsync(key, bytes);
            }
            batch.Execute();
        }
        /// <summary>
        /// set 出队
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public T SetPop<T>(string key)
        {
            //默认值
            var value = default(T);
            if (_Database == null || string.IsNullOrEmpty(key)) return value;
            try
            {
                var cacheValue = _Database.SetPop(key);
                if (!cacheValue.IsNull)
                {
                    byte[] bytes = (byte[])cacheValue;

                    if (bytes != null && bytes.Length > 0)
                    {
                        value = ByteSerializer.Deserialize<T>(bytes);
                    }
                    return value;
                }
            }
            catch (Exception ex)
            {
                LoggerHelper.Instance.Error("Cache-Redis" + ex.Message);
            }

            return value;
        }
        /// <summary>
        /// set 是否存在
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool IsExitSet(string key)
        {
            if (_Database == null || string.IsNullOrEmpty(key)) return false;
            return _Database.SetLength(key) > 0;
        }
    }
}
